/*
 * @Author: xuhongling
 * @Date:   2022-11-12 10:37:34
 * @Last Modified by:   xuhongling
 * @Last Modified time: 2025-07-03 22:38:39
 */
import { ref, unref, nextTick } from 'vue';
import Map from 'ol/Map';
import View from 'ol/View';
import { Tile as TileLayer } from 'ol/layer';
import { XYZ } from 'ol/source'
import * as olInteraction from 'ol/interaction';

// 地图对象
const globalOlMap = ref(null);

// 初始化地图
const initBasicOlMap = async (target) => {
  await nextTick();
  const wrapEl: any = unref(target);
  if (!wrapEl) {
    return;
  }

  // 天地图街道图 用的公司企业key
  /*const tileLayer = new TileLayer({
    source: new XYZ({
      url: 'http://58.51.99.14:58891/disk2/vec/{z}/{x}/{y}.png'
    }),
    visible: true
  });
  tileLayer.set('layerName', `tiandituTileLayer`);*/
  // 天地图街道图 路网标注
  /*const roadNet = new TileLayer({
    source: new XYZ({
      url: 'https://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=f630b1eca18e9c25011723e1d9b76584'
    }),
    visible: true
  });
  roadNet.set('layerName', `tiandituRoadNet`);*/

  // 天地图卫星图
  const satellite = new TileLayer({
    source: new XYZ({
      url: 'http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=f630b1eca18e9c25011723e1d9b76584'
    }),
    visible: true,
  });
  satellite.set('layerName', `tiandituSatellite`);

  // 天地图卫星图 路网标注
  const satelliteRoadNet = new TileLayer({
    source: new XYZ({
      url: 'https://t4.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=f630b1eca18e9c25011723e1d9b76584',
    }),
    visible: true,
  });
  satelliteRoadNet.set('layerName', `tiandituSatelliteRoadNet`);

  const olMap: any = new Map({
    target: wrapEl,
    layers: [satellite, satelliteRoadNet],
    view: new View({
      center: [115.617257, 30.020257],
      zoom: 6,
      minZoom: 5,
      maxZoom: 18,
      projection: 'EPSG:4326',
    }),
  });

  // 储存地图对象
  globalOlMap.value = olMap;

  // Openlayers 禁用鼠标双击缩放事件
  const dblClickInteraction = olMap
    .getInteractions()
    .getArray()
    .find((interaction: any) => {
      return interaction instanceof olInteraction.DoubleClickZoom;
    });
  olMap.removeInteraction(dblClickInteraction);

  // olMap.updateSize(); // openlayers 第一次加载黑屏修复，重新加载地图

  // 地图鼠标经过小手样式
  olMap.on('pointermove', (event: any) => {
    const pixel = event.map.getEventPixel(event.originalEvent);
    const feature = event.map.forEachFeatureAtPixel(pixel, (feature: any) => {
      return feature.getProperties();
    });
    if (feature === undefined) {
      event.map.getTargetElement().style.cursor = 'auto';
    } else {
      event.map.getTargetElement().style.cursor = 'pointer';
    }
  });
};

// 返回地图对象，供调用的组件使用
const getGlobalOlMap = () => {
  return globalOlMap.value;
}

export {
  initBasicOlMap,
  getGlobalOlMap
}
